Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new loader option "contextAsConfigBasePath", which when set to tr… #681

Merged
merged 4 commits into from
Nov 29, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,39 @@ loading only those files that are actually bundled by webpack, as well as any `.
by the `tsconfig.json` settings. `.d.ts` files are still included because they may be needed for
compilation without being explicitly imported, and therefore not picked up by webpack.

#### contextAsConfigBasePath *(boolean) (default=false)*

If true, will parse the TypeScript configuration file with
[webpack.context](https://webpack.js.org/configuration/entry-context/#context) as base path.
Per default the directory of the configuration file is used as base path. Relative paths in the configuration
file are resolved with respect to the base path when parsed. Option `contextAsConfigBasePath` allows to set option
`configFile` to a path other than the project root (e.g. a NPM package) and the base path for `ts-loader` is [webpack.context](https://webpack.js.org/configuration/entry-context/#context) (which is most of the time the project root).

Keep in mind that **not** having a `tsconfig.json` in your project root can cause different behaviour between `ts-loader` and `tsc`.
When using editors like `VS Code` it is advised to add a `tsconfig.json` file to the root of the project and extend the config file
referenced in option `configFile`.

Webpack:

```javascript
{
loader: require.resolve('ts-loader'),
options: {
contextAsConfigBasePath: true,
configFile: require.resolve('ts-config-react-app')
}
}

```

Extending `tsconfig.json`:

```json
{ "extends": "./node_modules/ts-config-react-app/index" }
```

Note that changes in the extending file while not be respected by `ts-loader`. Its purpose is to satisfy the code editor.

### `LoaderOptionsPlugin`

[There's a known "gotcha"](https://github.com/TypeStrong/ts-loader/issues/283) if you are using webpack 2 with the `LoaderOptionsPlugin`. If you are faced with the `Cannot read property 'unsafeCache' of undefined` error then you probably need to supply a `resolve` object as below: (Thanks @jeffijoe!)
Expand Down
4 changes: 2 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,12 @@ function findConfigFile(compiler: typeof typescript, requestDirPath: string, con
export function getConfigParseResult(
compiler: typeof typescript,
configFile: ConfigFile,
configFilePath: string
basePath: string
) {
const configParseResult = compiler.parseJsonConfigFileContent(
configFile.config,
compiler.sys,
path.dirname(configFilePath || '')
basePath
);

return configParseResult;
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ function getLoaderOptions(loader: Webpack) {
}

type ValidLoaderOptions = keyof LoaderOptions;
const validLoaderOptions: ValidLoaderOptions[] = ['silent', 'logLevel', 'logInfoToStdOut', 'instance', 'compiler', 'configFile', 'transpileOnly', 'ignoreDiagnostics', 'errorFormatter', 'colors', 'compilerOptions', 'appendTsSuffixTo', 'appendTsxSuffixTo', 'entryFileCannotBeJs' /* DEPRECATED */, 'onlyCompileBundledFiles', 'happyPackMode', 'getCustomTransformers'];
const validLoaderOptions: ValidLoaderOptions[] = ['silent', 'logLevel', 'logInfoToStdOut', 'instance', 'compiler', 'contextAsConfigBasePath', 'configFile', 'transpileOnly', 'ignoreDiagnostics', 'errorFormatter', 'colors', 'compilerOptions', 'appendTsSuffixTo', 'appendTsxSuffixTo', 'entryFileCannotBeJs' /* DEPRECATED */, 'onlyCompileBundledFiles', 'happyPackMode', 'getCustomTransformers'];

/**
* Validate the supplied loader options.
Expand Down Expand Up @@ -139,6 +139,7 @@ function makeLoaderOptions(instanceName: string, configFileOptions: Partial<Load
logInfoToStdOut: false,
compiler: 'typescript',
configFile: 'tsconfig.json',
contextAsConfigBasePath: false,
transpileOnly: false,
compilerOptions: {},
appendTsSuffixTo: [],
Expand Down
6 changes: 5 additions & 1 deletion src/instances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,11 @@ function successfulTypeScriptInstance(

const { configFilePath, configFile } = configFileAndPath;

const configParseResult = getConfigParseResult(compiler, configFile, configFilePath!);
const basePath = loaderOptions.contextAsConfigBasePath
? loader.context
: path.dirname(configFilePath || '');

const configParseResult = getConfigParseResult(compiler, configFile, basePath);

if (configParseResult.errors.length > 0 && !loaderOptions.happyPackMode) {
const errors = formatErrors(configParseResult.errors, loaderOptions, colors, compiler, { file: configFilePath });
Expand Down
1 change: 1 addition & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ export interface LoaderOptions {
instance: string;
compiler: string;
configFile: string;
contextAsConfigBasePath: boolean;
transpileOnly: boolean;
ignoreDiagnostics: number[];
errorFormatter: (message: ErrorInfo, colors: Chalk) => string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
/* 0 */
/***/ (function(module, exports) {

throw new Error("Module build failed: Error: ts-loader was supplied with an unexpected loader option: notRealOption\n\nPlease take a look at the options you are supplying; the following are valid options:\nsilent / logLevel / logInfoToStdOut / instance / compiler / configFile / transpileOnly / ignoreDiagnostics / errorFormatter / colors / compilerOptions / appendTsSuffixTo / appendTsxSuffixTo / entryFileCannotBeJs / onlyCompileBundledFiles / happyPackMode / getCustomTransformers\n\n at validateLoaderOptions (C:/source/ts-loader/dist/index.js:92:19)\n at getLoaderOptions (C:/source/ts-loader/dist/index.js:75:5)\n at Object.loader (C:/source/ts-loader/dist/index.js:23:19)");
throw new Error("Module build failed: Error: ts-loader was supplied with an unexpected loader option: notRealOption\n\nPlease take a look at the options you are supplying; the following are valid options:\nsilent / logLevel / logInfoToStdOut / instance / compiler / contextAsConfigBasePath / configFile / transpileOnly / ignoreDiagnostics / errorFormatter / colors / compilerOptions / appendTsSuffixTo / appendTsxSuffixTo / entryFileCannotBeJs / onlyCompileBundledFiles / happyPackMode / getCustomTransformers\n\n at validateLoaderOptions (C:/source/ts-loader/dist/index.js:92:19)\n at getLoaderOptions (C:/source/ts-loader/dist/index.js:75:5)\n at Object.loader (C:/source/ts-loader/dist/index.js:23:19)");

/***/ })
/******/ ]);
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ ERROR in ./.test/validateLoaderOptionNames/app.ts
Module build failed: Error: ts-loader was supplied with an unexpected loader option: notRealOption

Please take a look at the options you are supplying; the following are valid options:
silent / logLevel / logInfoToStdOut / instance / compiler / configFile / transpileOnly / ignoreDiagnostics / errorFormatter / colors / compilerOptions / appendTsSuffixTo / appendTsxSuffixTo / entryFileCannotBeJs / onlyCompileBundledFiles / happyPackMode / getCustomTransformers
silent / logLevel / logInfoToStdOut / instance / compiler / contextAsConfigBasePath / configFile / transpileOnly / ignoreDiagnostics / errorFormatter / colors / compilerOptions / appendTsSuffixTo / appendTsxSuffixTo / entryFileCannotBeJs / onlyCompileBundledFiles / happyPackMode / getCustomTransformers

at validateLoaderOptions (dist\index.js:92:19)
at getLoaderOptions (dist\index.js:75:5)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
/* 0 */
/***/ (function(module, exports) {

throw new Error("Module build failed: Error: ts-loader was supplied with an unexpected loader option: notRealOption\n\nPlease take a look at the options you are supplying; the following are valid options:\nsilent / logLevel / logInfoToStdOut / instance / compiler / configFile / transpileOnly / ignoreDiagnostics / errorFormatter / colors / compilerOptions / appendTsSuffixTo / appendTsxSuffixTo / entryFileCannotBeJs / onlyCompileBundledFiles / happyPackMode / getCustomTransformers\n\n at validateLoaderOptions (C:/source/ts-loader/dist/index.js:92:19)\n at getLoaderOptions (C:/source/ts-loader/dist/index.js:75:5)\n at Object.loader (C:/source/ts-loader/dist/index.js:23:19)");
throw new Error("Module build failed: Error: ts-loader was supplied with an unexpected loader option: notRealOption\n\nPlease take a look at the options you are supplying; the following are valid options:\nsilent / logLevel / logInfoToStdOut / instance / compiler / contextAsConfigBasePath / configFile / transpileOnly / ignoreDiagnostics / errorFormatter / colors / compilerOptions / appendTsSuffixTo / appendTsxSuffixTo / entryFileCannotBeJs / onlyCompileBundledFiles / happyPackMode / getCustomTransformers\n\n at validateLoaderOptions (C:/source/ts-loader/dist/index.js:92:19)\n at getLoaderOptions (C:/source/ts-loader/dist/index.js:75:5)\n at Object.loader (C:/source/ts-loader/dist/index.js:23:19)");

/***/ })
/******/ ]);
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ ERROR in ./.test/validateLoaderOptionNames/app.ts
Module build failed: Error: ts-loader was supplied with an unexpected loader option: notRealOption

Please take a look at the options you are supplying; the following are valid options:
silent / logLevel / logInfoToStdOut / instance / compiler / configFile / transpileOnly / ignoreDiagnostics / errorFormatter / colors / compilerOptions / appendTsSuffixTo / appendTsxSuffixTo / entryFileCannotBeJs / onlyCompileBundledFiles / happyPackMode / getCustomTransformers
silent / logLevel / logInfoToStdOut / instance / compiler / contextAsConfigBasePath / configFile / transpileOnly / ignoreDiagnostics / errorFormatter / colors / compilerOptions / appendTsSuffixTo / appendTsxSuffixTo / entryFileCannotBeJs / onlyCompileBundledFiles / happyPackMode / getCustomTransformers

at validateLoaderOptions (dist\index.js:92:19)
at getLoaderOptions (dist\index.js:75:5)
Expand Down
45 changes: 45 additions & 0 deletions test/execution-tests/option-contextAsConfigBasePath/karma.conf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* eslint-disable no-var, strict */
'use strict';
var webpackConfig = require('./webpack.config.js');
var reporterOptions = require('../../reporterOptions');

module.exports = function(config) {
// Documentation: https://karma-runner.github.io/0.13/config/configuration-file.html
config.set({
browsers: [ 'ChromeHeadless' ],

files: [
// This ensures we have the es6 shims in place and then loads all the tests
'main.js'
],

port: 9876,

frameworks: [ 'jasmine' ],

logLevel: config.LOG_INFO, //config.LOG_DEBUG

preprocessors: {
'main.js': [ 'webpack', 'sourcemap' ]
},

webpack: {
devtool: 'inline-source-map',
module: webpackConfig.module,
resolve: webpackConfig.resolve,

// for test harness purposes only, you would not need this in a normal project
resolveLoader: webpackConfig.resolveLoader
},

webpackMiddleware: {
quiet: true,
stats: {
colors: true
}
},

// reporter options
mochaReporter: reporterOptions
});
};
4 changes: 4 additions & 0 deletions test/execution-tests/option-contextAsConfigBasePath/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import 'babel-polyfill';

const testsContext = require.context('./', true, /\.tests\.ts(x?)$/);
testsContext.keys().forEach(testsContext);
26 changes: 26 additions & 0 deletions test/execution-tests/option-contextAsConfigBasePath/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "es6-babel-react",
"license": "MIT",
"version": "1.0.0",
"main": "index.js",
"devDependencies": {
"@types/jasmine": "^2.5.35",
"@types/react": "^0.14.41",
"@types/react-addons-test-utils": "^0.14.15",
"@types/react-test-renderer": "^15.5.0",
"@types/react-dom": "^0.14.18",
"babel": "^6.0.0",
"babel-core": "^6.0.0",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.0.0",
"babel-preset-react": "^6.0.0",
"jasmine-core": "^2.3.4",
"react-addons-test-utils": "^15.3.1",
"react-test-renderer": "^15.5.4"
},
"dependencies": {
"babel-polyfill": "^6.0.0",
"react": "^15.4.1",
"react-dom": "^15.4.1"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import React from 'react';

const App: React.SFC<{ name: string }> = ({ name }) =>
<div className="container-fluid">
<h1>Hello {name}!</h1>
</div>;

export default App;
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';

import App from './components/App';

ReactDOM.render(<App name="James" />, document.getElementById('content'));
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React from 'react';
import { createRenderer } from 'react-test-renderer/shallow';

import App from '../../src/components/App';

describe('App', () => {
it('simple', () => expect(1).toBe(1));

it('renders expected HTML', () => {
const shallowRenderer = createRenderer();

shallowRenderer.render(<App name="James" />);
const app = shallowRenderer.getRenderOutput();

expect(app).toEqual(
<div className="container-fluid">
<h1>Hello { "James" }!</h1>
</div>
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"lib": [
"dom",
"es2015"
],
"jsx": "preserve",
"target": "es2015",
"module": "es2015",
"moduleResolution": "node",
"noImplicitAny": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": false,
"preserveConstEnums": true,
"sourceMap": true,
"skipLibCheck": true
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/* eslint-disable no-var, strict, prefer-arrow-callback */
'use strict';

var path = require('path');
var webpack = require('webpack');

var babelOptions = {
"presets": [
"react",
[
"es2015",
{
"modules": false
}
],
"es2016"
]
};

module.exports = {
entry: './src/main.tsx',
output: {
filename: 'bundle.js'
},
module: {
rules: [{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: babelOptions
},
{
loader: 'ts-loader',
options: {
contextAsConfigBasePath: true,
configFile: require.resolve('./tsconfig-container/tsconfig.json')
}
}
]
}, {
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: babelOptions
}
]
}]
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: ['.ts', '.tsx', '.js']
},
};

// for test harness purposes only, you would not need this in a normal project
module.exports.resolveLoader = { alias: { 'ts-loader': path.join(__dirname, "../../../index.js") } }